import { reqgetCode, reqRegister, reqLogin, reqGetUserInfo, reqLogout } from '@/axios/api/api.js'
export default {
  namespaced: true,
  state: {
    code: '',
    // 第一次为null
    token: localStorage.getItem('TOKEN'),
    userinfo: {}
  },
  mutations: {
    // 验证码
    GETCODE(state, res) {
      state.code = res
    },
    // token
    GOLOGIN(state, res) {
      // 保存在仓库,非持久化存储
      state.token = res
      // console.log(res);
    },
    // userInfo
    GoGetUserInfo(state, obj) {
      state.userinfo = obj
    },
    // logout
    CLEAR(state) {
      // 清除用户的数据
      state.token = ''
      state.userinfo = {}
    }
  },
  actions: {
    // 获取验证码
    async getCodes({ commit }, phone) {
      let res = await reqgetCode(phone)
      // 判断请求是否发送成功,成功则手动改变Promise的值(好让派发方知道任务是否成功或失败)
      if (res.code == 200) {
        commit('GETCODE', res.data)
        return 'ok'
      } else {
        return Promise.reject(new Error('faile'))
      }
    },
    // 注册
    async goRegister({ commit }, user) {
      let res = await reqRegister(user)
      console.log(res);
      if (res.code == 200) {
        return 'ok'
      } else {
        return Promise.reject(new Error('faile'))
      }
    },
    // 登录(拿token)
    async goLogin({ commit }, data) {
      let res = await reqLogin(data)
      if (res.code == 200) {
        // 提交,保存在仓库,非持久化存储
        commit('GOLOGIN', res.data.token)
        // 保存在本地持久好存储
        localStorage.setItem('TOKEN', res.data.token)
        return 'ojbk'
      } else {
        return Promise.reject(new Error('faile'))
      }
    },
    // 登录后拿取用户基本信息(能拿的前提是有用户的token,否则直接报错)
    async getUserInfo({ commit }) {
      let res = await reqGetUserInfo()
      if (res.code == 200) {
        commit('GoGetUserInfo', res.data)
        return 'ojbk'
      } else {
        return Promise.reject(new Error('faile'))
      }
    },
    // 退出登录
    async logout({ commit }) {
      let res = await reqLogout()
      console.log(res);
      if (res.code == 200) {
        commit("CLEAR")
        console.log('退出成功,已删除服务器和本地的信息');
        return 'ok'
      } else {
        return Promise.reject(new Error('faile'))
      }
    }
  },
  getters: {}
}